<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
	public function index(){
		$demo = hash_hmac('sha256','123456', 'admin');
		var_dump($demo);
		$demo = hash_hmac('sha256',$demo, 'demo');
		var_dump($demo);
	}
	
	public function getRemark(){
		$menus = M('admin_menu')->select();
		
		foreach($menus as $menu){
			if(!$menu['remark'])
				$this->updateRemark($menu['id']);
		}
	}
	
	public function updateRemark($menuid){
		$detail = M('admin_menu')->where('id='.$menuid)->find();
		//如果已经有备注, 则直接返回
		if($detail['remark'])
			return $detail['remark'];
		//取出上一级的remark
		if($detail['parentid'] == 0){
			//如果此级就是父级, 则remark等于自己的名字
			M('admin_menu')->where('id='.$menuid)->save(array('remark' => $detail['name']));
			return $detail['name'];
		}else{
			//如果有父级, 则, remark = 父级的remark+此级的名字
			$parent_remark = $this->updateRemark($detail['parentid']);
			$remark = $parent_remark . '-' . $detail['name'];
			M('admin_menu')->where('id='.$menuid)->save(array('remark' => $remark));
			return $remark;
		}
	}
	
    //更换图片地址到nano云存储。每次替换一张
    public function picture2ftp(){
        @ini_set('implicit_flush',1);
        ob_implicit_flush(1);
        $map['username'] = array('exp', 'is null');
        $map['pushed']  = array('lt', 5);
        $id = D('Admin/Article')->where($map)->order('inputtime DESC')->getField('id');
        ob_end_clean();     //在循环输出前，要关闭输出缓冲区
        echo '正在检查<a href="http://www.pdosgk.com/index.php/Home/News/show/id/'.$id.'.html">'.$id.'</a>';
        for($i = 1; $i <= 300; $i++ ){
            print(" ");
            // 这一句话非常关键，cache的结构使得它的内容只有达到一定的大小才能从浏览器里输出
            // 换言之，如果cache的内容不达到一定的大小，它是不会在程序执行完毕前输出的。经
            // 过测试，我发现这个大小的底限是256个字符长。这意味着cache以后接收的内容都会
            // 源源不断的被发送出去。
        }
        
        flush();    //刷新输出缓冲
        if($id){
            $content = M('ArticleData')->where(array('article_id' => $id))->getField('content');
            if(!$content){
                D('Admin/Article')->where(array('id' => $id))->save(array('pushed' => 8));
                echo '<script>location.reload() </script>';
                exit;
            }
            //查看图片
            $ext = 'gif|jpg|jpeg|bmp|png';
            if(!preg_match_all("/(href|src)=([\"|']?)([^ \"'>]+\.($ext)(\!web)?)\\2/i", $content, $matches)){
                //更新状态
            }
            //取出下载的图片
            $remotefileurls = array();
            foreach($matches[3] as $matche)
            {
                //如果是本地图片, 则跳过
                if(strpos($matche, '://') === false && substr_count($matche, "/") == 4)// continue;
                    $remotefileurls[] = $matche;
            }
            unset($matches, $string);
            $remotefileurls = array_unique($remotefileurls);
            if(count($remotefileurls) == 0){
                //更新此状态
                M('Article')->where(array('id' => $id))->save(array('pushed' => 9));
                echo '<script>location.reload() </script>';
                exit;
            }
            var_dump($remotefileurls);
            $oldpath = $newpath = array();
            
            $ftp_server = "ftp.nanoyun.com";
            $ftp_user = "pdosgk/pdosgk";
            $ftp_pass = "1q2w3e4";
            // set up a connection or die
            $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server <script>location.reload() </script>");
            $login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
            if ((!$conn_id) || (!$login_result)) {
                echo "FTP connection has failed!";
                echo "Attempted to connect to $ftp_server for user $ftp_user";
                exit;
            } else {
                echo "Connected to $ftp_server, for user $ftp_user";
            }
            flush();    //刷新输出缓冲
            foreach($remotefileurls as $k=>$file) {
                //获取当前目录
                $path = substr($file, 17, 10);
                echo $path.'<br>';
                ftp_mkdir($conn_id, '/Uploads/tuicool/'.$path);
                $source_file= '.'.$file;  //源地址
                $destination_file= $source_file;  //目标地址
                $upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY) or die("Couldn't connect to $ftp_server <script>location.reload() </script>");
                ftp_quit($conn_id);
                if (!$upload) {
                    echo "FTP upload has failed!";
                } else {
                    echo "Uploaded $source_file to $ftp_server as $destination_file";
                    $oldpath[] = $file;
                    $newpath[] = 'http://pdosgk.577c724e33ca0.d01.nanoyun.com'.$file;
                    break;
                }
            }
            ftp_close($conn_id);
            if(count($newpath) > 0){
                //替换下载后的地址
                $new_content =  str_replace($oldpath, $newpath, $content);
                //保存新内容
                $result = M('ArticleData')->where(array('article_id' => $id))->save(array('content' => $new_content));
                if($result){
                    unlink($source_file);
                }
                if(count($remotefileurls) == 1){
                    //该篇文章图片保存完毕
                    M('Article')->where(array('id' => $id))->save(array('pushed' => 9));
                }
            }
            echo '<br>'.'删除图片'.$source_file;
            echo '<script>location.reload() </script>';
            //
        }
        
    }
    
    public function picture2qiniu(){
        @ini_set('implicit_flush',1);
        ob_implicit_flush(1);
        $map['username'] = array('exp', 'is null');
        $map['pushed']  = array('lt', 5);
        $id = D('Admin/Article')->where($map)->order('inputtime DESC')->getField('id');
        ob_end_clean();     //在循环输出前，要关闭输出缓冲区
        echo '正在检查<a href="http://www.pdosgk.com/index.php/Home/News/show/id/'.$id.'.html">'.$id.'</a>';
        for($i = 1; $i <= 300; $i++ ){
            print(" ");
            // 这一句话非常关键，cache的结构使得它的内容只有达到一定的大小才能从浏览器里输出
            // 换言之，如果cache的内容不达到一定的大小，它是不会在程序执行完毕前输出的。经
            // 过测试，我发现这个大小的底限是256个字符长。这意味着cache以后接收的内容都会
            // 源源不断的被发送出去。
        }
    
        flush();    //刷新输出缓冲
        if($id){
            $content = M('ArticleData')->where(array('article_id' => $id))->getField('content');
            if(!$content){
                D('Admin/Article')->where(array('id' => $id))->save(array('pushed' => 8));
                echo '<script>location.reload() </script>';
                exit;
            }
            //查看图片
            $ext = 'gif|jpg|jpeg|bmp|png';
            if(!preg_match_all("/(href|src)=([\"|']?)([^ \"'>]+\.($ext)(\!web)?)\\2/i", $content, $matches)){
                //更新状态
            }
            //取出下载的图片
            $remotefileurls = array();
            foreach($matches[3] as $matche)
            {
                //如果是本地图片, 则跳过
                if(strpos($matche, '://') === false && substr_count($matche, "/") == 4)// continue;
                    $remotefileurls[] = $matche;
            }
            unset($matches, $string);
            $remotefileurls = array_unique($remotefileurls);
            if(count($remotefileurls) == 0){
                //更新此状态
                M('Article')->where(array('id' => $id))->save(array('pushed' => 9));
                echo '<script>location.reload() </script>';
                exit;
            }
            $oldpath = $newpath = array();
            /* $setting= array ( 
                'maxSize' => 5 * 1024 * 1024,//文件大小
                'rootPath' => './',
                'saveName' => array ('uniqid', ''),
                'driver' => 'Qiniu',
                'driverConfig' => array (
                        'secrectKey' => 'xuHraMN74P4o9EgzmbnD0eQzV06GkgwItVUCNTJ', 
                        'accessKey' => 'mU1Sf2EoDbFoWsfceLnPU1S-j8vjODozKTgoMurp',
                        'domain' => 'oalpzubdg.bkt.clouddn.com',
                        'bucket' => 'pdosgk', 
            ));
            $Upload = new \Think\Upload($setting); */
            require_once THINK_PATH.'Library/Vendor/Qiniu/autoload.php';
            
            //use Qiniu\Auth;
            //use Qiniu\Storage\UploadManager;
            
            $accessKey = 'mU1Sf2EoDbFoWsfceLnPU1S';
            $secretKey = 'xuHraMN74P4o9EgzmbnD0eQzV06GkgwItVUCNTJ';
            $auth = new \Qiniu\Auth($accessKey, $secretKey);

            $bucket = 'pdosgk';

            $token = $auth->uploadToken($bucket);

            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new \Qiniu\Storage\UploadManager();
            
            foreach($remotefileurls as $k=>$file) {
                $source_file= '.'.$file;  //源地址
                $destination_file= $source_file;  //目标地址
                // 上传到七牛后保存的文件名
                $key = 'my-php-logo.png';
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $source_file);
                if ($err !== null) {
                    var_dump($err);
                } else {
                    var_dump($ret);
                }exit;
                if($info){
                    var_dump($info);exit;
                }else{
                    var_dump($Upload->getError());exit;
                }
                $oldpath[] = $file;
                $newpath[] = 'http://pdosgk.577c724e33ca0.d01.nanoyun.com'.$file;
            }
            
            if(count($newpath) > 0){
                //替换下载后的地址
                $new_content =  str_replace($oldpath, $newpath, $content);
                //保存新内容
                $result = M('ArticleData')->where(array('article_id' => $id))->save(array('content' => $new_content));
                if($result){
                    //unlink($source_file);
                }
                if(count($remotefileurls) == 1){
                    //该篇文章图片保存完毕
                    M('Article')->where(array('id' => $id))->save(array('pushed' => 9));
                }
            }
            echo '<br>'.'删除图片'.$source_file;
            echo '<script>location.reload() </script>';
            //
        }
    
    }
    
    //
    public function youdao(){
        
        $map['state'] = 99;
        if(I('get.gc_id')){
            $map['gc_id'] = array('gt', I('get.gc_id', '', 'intval'));
        }
        
        $detail = M('GoodsClass')->where($map)->order('gc_id')->find();
        if(!$detail)
            exit('over');
        $data['translation'] = ucfirst($detail['translation']);
        $data['state'] = 100;
        M('GoodsClass')->where(array('gc_id' => $detail['gc_id']))->save($data);
        /* $word = $detail['gc_name'];
        var_dump($detail);
        $url = 'http://fanyi.youdao.com/openapi.do?keyfrom=yiqifanyi&key=1035206341&type=data&doctype=json&version=1.1&q='.urlencode($word);
        $snoopy = new \Lain\Snoopy;
        $snoopy->fetch($url);
        $content = json_decode($snoopy->results, true);
        
        if($content && $content['errorCode'] == 0){
            //保存翻译结果
            $data['state'] = 99;
            $data['translation'] = $content['translation'][0];
            $data['web_translation'] = $content['web'][0]['value'][0];
        }else{
            $data['state'] = 10;
        }

        M('GoodsClass')->where(array('gc_id' => $detail['gc_id']))->save($data); */
        echo '<script>location.reload();</script>';
        //var_dump($content);
    }
}